"use client";
import type { Config } from "@/lib/api/system/config.d";
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
  ProTableProps,
} from "@ant-design/pro-components";
import { Button, message, Popconfirm, Space, Tag } from "antd";
import { useRouter } from "next/navigation";
import { useRequest } from "ahooks";
import { useRef } from "react";
import { deleteConfigApi, getConfigListApi } from "@/lib/api/system/config";
import { download } from "@/lib/utils/file";

export default function Page() {
  const router = useRouter();
  const actionRef = useRef<ActionType>();

  const { run: deleteConfig } = useRequest(deleteConfigApi, {
    manual: true,
    onSuccess: () => {
      message.success("删除成功");
      actionRef.current?.reload();
    },
    onError: () => {
      message.error("删除失败");
    },
  });

  const { loading: exportConfigLoading, run: exportConfig } = useRequest(
    () => download("/system/config/export", {}, "config.xlsx"),
    {
      manual: true,
      onSuccess: () => {
        message.success("导出成功");
      },
    },
  );

  const colums: ProColumns<Config>[] = [
    {
      title: "参数名称",
      dataIndex: "configName",
      key: "configName",
    },
    {
      title: "参数键名",
      dataIndex: "configKey",
      key: "configKey",
    },
    {
      title: "参数键值",
      dataIndex: "configValue",
      key: "configValue",
    },
    {
      title: "系统内置",
      dataIndex: "configType",
      key: "configType",
      width: 100,
      valueEnum: {
        Y: "是",
        N: "否",
      },
      render: (_, record) => (
        <Tag color={record.configType === "Y" ? "green" : "red"}>
          {record.configType === "Y" ? "是" : "否"}
        </Tag>
      ),
    },
    {
      title: "备注",
      dataIndex: "remark",
      key: "remark",
      ellipsis: true,
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      valueType: "dateTime",
      width: 150,
      hideInSearch: true,
    },
    {
      title: "操作",
      key: "action",
      search: false,
      width: 150,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => editHandler(record.configId)}>
            修改
          </Button>
          <Popconfirm
            title="确定删除吗？"
            description="删除后将无法恢复！"
            onConfirm={() => {
              deleteConfig(record.configId);
            }}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const proTableProps: ProTableProps<Config, any> = {
    columns: colums,
    rowKey: "configId",
    pagination: {
      pageSize: 10,
    },
    headerTitle: "角色列表",
    expandable: {
      defaultExpandAllRows: true,
    },
    actionRef: actionRef,
    options: {
      fullScreen: true,
    },
    toolBarRender: () => {
      return [
        <Button onClick={() => addHandler()} key="add" type="primary">
          新增
        </Button>,
        <Button
          onClick={() => exportConfig()}
          loading={exportConfigLoading}
          key="export"
          type="primary"
        >
          导出
        </Button>,
      ];
    },
    request: async (params) => {
      const res = await getConfigListApi(params);

      return {
        data: res.rows,
        total: res.total,
        success: true,
      };
    },
    onRequestError(e) {
      message.error(e.message);
    },
  };

  const addHandler = () => {
    router.push(`config/add`);
  };

  const editHandler = (configId: string) => {
    router.push(`config/edit?configId=${configId}`);
  };

  return (
    <PageContainer
      header={{
        title: false,
      }}
    >
      <ProTable {...proTableProps}></ProTable>
    </PageContainer>
  );
}
